package com.itheima.security.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.security.mapper.UserMapper;
import com.itheima.security.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    UserMapper userMapper;

    /**
     * 当点击的登录时，执行此方法
     *
     * 方法作用： 根据用户名查询用户信息，并返回
     *
     * AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()): 把权限字符串，转换为 权限List集合
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名 查询数据库中的用户信息
        LambdaQueryWrapper<User> userQw = new LambdaQueryWrapper<>();
        userQw.eq(User::getUsername, username);
        User user = userMapper.selectOne(userQw);
        //如果查不到， 说明用户名不存在
        //如果查到了， 说明用户存在
        if(user != null){
            org.springframework.security.core.userdetails.User userDetails =
                    new org.springframework.security.core.userdetails.User(
                            username, user.getPassword(),
                            AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));
            return userDetails;
        }

        return null;
    }
}
